package com.diu.domain.strategy.service.rule.chain.factory;

import com.diu.domain.strategy.model.entity.StrategyEntity;
import com.diu.domain.strategy.model.entity.StrategyRuleEntity;
import com.diu.domain.strategy.repository.IStrategyRepository;
import com.diu.domain.strategy.service.rule.chain.ILogicChain;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author #diu
 * @description #
 * @create #2025/10/14 11:49
 */
@Service
public class DefaultChainFactory {

    private final IStrategyRepository repository;

    private final Map<String,ILogicChain> logicChainGroup;
    // 通过构造函数注入
    public DefaultChainFactory(IStrategyRepository repository, Map<String, ILogicChain> logicChainGroup) {
        this.repository = repository;
        this.logicChainGroup = logicChainGroup;
    }

    public ILogicChain openLogicChain(Long strategyId){
        StrategyEntity ruleEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String[] ruleModels = ruleEntity.ruleModels();

        if(null == ruleModels || ruleModels.length == 0) return logicChainGroup.get("default");
        ILogicChain beginChain = logicChainGroup.get(ruleModels[0]);
        ILogicChain current = beginChain;
        // 组装责任链 length-1保证current不会变成null
        for(int i=1;i<ruleModels.length;i++){
            current = current.appendNext(logicChainGroup.get(ruleModels[i]));
        }
        // 兜底责任链节点
        current.appendNext(logicChainGroup.get("default"));
        return beginChain;
    }
}
